package com.bauer.module.common.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

import java.security.Key;
import java.util.Arrays;

/**
 * @program: clock
 * @description:
 * @author: bauer weo
 * @create: 2019-09-24 22:03
 */
public class AESUtil {

    private static final String ALGORITHM = "AES";

    private static final String key = "1897asba87213jbhadu87asdfb2387";

    private static Key toKey(byte[] key) {

        SecretKey secretKey = new SecretKeySpec(key, "AES");

        return secretKey;

    }

    public static String encrypt(String data, String key) {
        try {
            String secretKey = getSecretKey(key);
            Key k = toKey(Base64.decodeBase64(secretKey));

            byte[] raw = k.getEncoded();

            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");

            Cipher cipher = Cipher.getInstance("AES");

            cipher.init(1, secretKeySpec);

            byte[] bytes = cipher.doFinal(data.getBytes("UTF-8"));

            return Base64.encodeBase64String(bytes);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String data, String key) {

        try {
            String secretKey = getSecretKey(key);

            Key k = toKey(Base64.decodeBase64(secretKey));

            byte[] raw = k.getEncoded();

            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");

            Cipher cipher = Cipher.getInstance("AES");

            cipher.init(2, secretKeySpec);

            byte[] bytes = cipher.doFinal(Base64.decodeBase64(data));

            return new String(bytes, "UTF-8");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    public static String getSecretKey(String encrypted) throws Throwable {

        byte[] bytes = encrypted.getBytes("ISO8859-1");

        bytes = Arrays.copyOf(bytes, 16);

        return Base64.encodeBase64String(bytes);

    }

    public static String decrypt(String data) {

        String decryptData = "";

        try {

            String secrtKey = getSecretKey(key);

            decryptData = decrypt(data, secrtKey);

        } catch (Throwable e) {

            e.printStackTrace();

        }

        return decryptData;

    }

    public static String encrypt(String data) throws Throwable {

        String secretKey = getSecretKey(key);

        return encrypt(data, secretKey);

    }

    public static void main(String[] args) throws Throwable {

        String data = "Abl20171026";

        String encryptData = encrypt(data,"xxx");

        System.out.println("加密后数据" + encryptData);

        System.out.println("解密后数据" + decrypt(encryptData,"xxx"));

    }

}
